<?php
namespace App\Lib;

class Db
{
    private $dbConfig;

    public function __construct()
    {
        $this->dbConfig = require CONFIG_DIR . DIRECTORY_SEPARATOR . 'db.php';
    }

    /**
     * 执行增删改SQL语句
     *
     * @param $sql
     * @param array $params 预处理语句参数按顺序构成的数组
     * @return true表示语句执行成功
     */
    public function execute($sql, $params = [])
    {
        try {
            $dsn = 'mysql:host=' . $this->dbConfig['host'] . ';dbname=' . $this->dbConfig['db'];
            $conn = new \PDO($dsn, $this->dbConfig['username'], $this->dbConfig['password']);
            $stmt = $conn->prepare($sql);
            for ($i = 0; $i < count($params); $i++) {
                $stmt->bindParam($i + 1, $params[$i]);
            }
            if ($stmt->execute()) {
                return true;
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        return false;
    }

    /**
     * 执行SQL查询语句
     *
     * @param $sql
     * @param array $params 预处理语句参数按顺序构成的数组
     * @return array 返回包含查询结果数据的数组
     */
    public function query($sql, $params = [])
    {
        $data = [];
        try {
            $dsn = 'mysql:host=' . $this->dbConfig['host'] . ';dbname=' . $this->dbConfig['db'];
            $conn = new \PDO($dsn, $this->dbConfig['username'], $this->dbConfig['password']);
            $stmt = $conn->prepare($sql);
            for ($i = 0; $i < count($params); $i++) {
                $stmt->bindParam($i + 1, $params[$i]);
            }
            if ($stmt->execute()) {
                while ($obj = $stmt->fetchObject()) {
                    array_push($data, $obj);
                }
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        return $data;
    }
}
